package report

import (
	"context"
	"sale-admin/internal/models"
	"strings"
	"time"

	"192.168.1.75/go-pkg/errorx"
	"192.168.1.75/go-pkg/helper"
	"gorm.io/gorm"
)

type EventQuestionService struct{}

func (eq EventQuestionService) AddEventQuestion(ctx context.Context, db *gorm.DB, eventType, content string) (err error) {
	var typeCount int64
	db.Model(&models.MaEventType{}).Where("id = ?", eventType).Count(&typeCount)
	if typeCount == 0 {
		err = errorx.New("事件类型不存在", -1)
		return
	}
	if strings.TrimSpace(content) == "" {
		err = errorx.New("事件问题不能为空", -1)
		return
	}
	var InsertData models.MaEventQuestion
	InsertData.AddTime = time.Now()
	InsertData.EventType = eventType
	InsertData.Content = content
	db.Model(&models.MaEventQuestion{}).Create(&InsertData)
	return
}
func (eq EventQuestionService) EditEventQuestion(ctx context.Context, db *gorm.DB, id, eventType, content string) (err error) {
	var typeCount int64
	db.Model(&models.MaEventType{}).Where("id = ?", eventType).Count(&typeCount)
	if typeCount == 0 {
		err = errorx.New("事件类型不存在", -1)
		return
	}
	var count int64
	db.Model(&models.MaEventQuestion{}).Where("id = ?", id).Count(&count)
	if count == 0 {
		err = errorx.New("事件问题不存在", -1)
		return
	}
	db.Model(&models.MaEventQuestion{}).Where("id = ?", id).
		Updates(map[string]interface{}{
			"event_type": eventType,
			"content":    content,
		})
	return
}

func (eq EventQuestionService) EventQuestionList(ctx context.Context, db *gorm.DB, page, limit int) (data []models.MaEventQuestion, count int64, err error) {
	tx := db.Model(&models.MaEventQuestion{})
	tx.Count(&count)
	var res = []models.MaEventQuestion{}
	helper.Gorm{}.Paginate(tx, page, limit).Find(&res)
	return res, count, nil
}

func (eq EventQuestionService) DelEventQuestion(ctx context.Context, db *gorm.DB, ID string) (err error) {
	db.Model(&models.MaEventQuestion{}).Where("id = ?", ID).
		Delete(&models.MaEventQuestion{})
	return
}
